/***************************************************
> Copyright (C) 2024 ==QWZL== All rights reserved.
> File Name: queryLog.c
> Author:nxq
> Mail:nxq949698473@163.com 
> Created Time: 2024年07月28日 星期日 01时20分21秒
***************************************************/

#include "queryLog.h"

//查询日志
void logQuery(char*buf,int sock)
{
    char sql[100] = {0};

    MYSQL *mysql = NULL;
  	MYSQL *rs = NULL;
    mysql = mysql_init(NULL);

	rs = mysql_real_connect(mysql,"localhost","","","water",0,NULL,0);
	if(rs == NULL)
	{
		LOG_E("%s\n",mysql_error(mysql));
		mysql_close(mysql);
		exit(-1);
 	}

    strcpy(sql,"select * from logTable");
    int ret = 0;
	ret = mysql_query(mysql,sql);
	if(ret != 0)
	{
		LOG_E("%s\n",mysql_error(mysql));
		mysql_close(mysql);
		exit(-1);
	}
    char type[1024];
    memset(&type,0,strlen(type));
	MYSQL_RES *res = NULL;
	MYSQL_ROW row = NULL;

    struct query query;
    memset(&query,0,sizeof(query));

	res = mysql_store_result(mysql);//把查询的数据取出，放到mysql中
    row = mysql_fetch_row(res);

    cJSON *json = NULL;
    
    while(row != NULL)
    {
        strcpy(type,"begin");
        query.id= atoi(row[0]);
        strcpy(query.event,row[1]);
        strcpy(query.time,row[2]);

        json = cJSON_CreateObject();
        
        //添加多个"键-值”对
        cJSON_AddItemToObject(json,"type",cJSON_CreateString(type));
        cJSON_AddItemToObject(json,"id",cJSON_CreateNumber(query.id));
        cJSON_AddItemToObject(json,"event",cJSON_CreateString(query.event));
        cJSON_AddItemToObject(json,"time",cJSON_CreateString(query.time));
        
        //将json对象转成json格式字符串
        char *p = cJSON_Print(json);
        printf("%s\n",p);
        //发送
        ret = send(sock,p,strlen(p),0);
        if(ret == -1)
        {
            perror("send\n");
            exit(-1);
        
        }   
        memset(p,0,strlen(p));
        row = mysql_fetch_row(res);
        sleep(1);
    }

    //给发送结束标志
    strcpy(type,"over"); 
    query.id = 0;
    strcpy(query.event,"0");
    strcpy(query.time,"0");

    json = cJSON_CreateObject();
        
    //添加多个"键-值”对
    cJSON_AddItemToObject(json,"type",cJSON_CreateString(type));
    cJSON_AddItemToObject(json,"id",cJSON_CreateNumber(query.id));
    cJSON_AddItemToObject(json,"event",cJSON_CreateString(query.event));
    cJSON_AddItemToObject(json,"time",cJSON_CreateString(query.time));

    char *p = cJSON_Print(json);
    
    ret = send(sock,p,strlen(p),0);
    if(ret == -1)
    {
        LOG_E("send\n");
        exit(-1);
    
    } 

    printf("发送完成！\n");
    mysql_free_result(res);
    mysql_close(mysql);

    cJSON_Delete(json);
}
